package com.example.ymm.modules1.service.impl.user;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.my.user.DbChatGroup;
import com.example.ymm.modules1.entity.my.user.DbChatGroupDept;
import com.example.ymm.modules1.entity.my.user.DbDeptUser;
import com.example.ymm.modules1.mapper.my.user.DbChatGroupDeptMapper;
import com.example.ymm.modules1.query.DbChatGroupDeptQueryCriteria;
import com.example.ymm.modules1.service.dto.DbDeptUserDto;
import com.example.ymm.modules1.service.dto.DbDeptUserQueryCriteria;
import com.example.ymm.modules1.service.user.*;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class DbChatGroupDeptServiceImpl extends BaseServiceImpl<DbChatGroupDeptMapper, DbChatGroupDept> implements DbChatGroupDeptService {

    @Autowired
    DbDeptService deptService;
    @Autowired
    DbDeptUserService dbDeptUserService;

    @Autowired
    DbChatGroupUserService dbChatGroupUserService;
    @Autowired
    DbChatGroupService dbChatGroupService;

    @Override
    public TableList<DbChatGroupDept> list(DbChatGroupDeptQueryCriteria criteria, YmPageDto pageDto) {
        IPage<DbChatGroupDept> page = new Page<DbChatGroupDept>(pageDto.getPage(),pageDto.getPageSize());
        baseMapper.selectPage(page, QueryHelpPlus.getPredicate(DbChatGroupDept.class, criteria));
        TableList<DbChatGroupDept> tableList=new TableList(page);
        return tableList;
    }

    public List<DbChatGroupDept> queryAll(DbChatGroupDeptQueryCriteria criteria) {
        List<DbChatGroupDept> result =baseMapper.selectList(QueryHelpPlus.getPredicate(DbChatGroupDept.class, criteria));
        return result;
    }

    @Override
    public void setDepts(String openConversationId, String deptIds,String deptNames) {
//        DbChatGroupDeptQueryCriteria criteria=new DbChatGroupDeptQueryCriteria();
//        criteria.setOpenConversationId(openConversationId);
        LambdaQueryWrapper<DbChatGroupDept> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DbChatGroupDept::getOpenConversationId,openConversationId);
        remove(lambdaQueryWrapper);
        String[] split = deptIds.split(",");
        List<DbChatGroupDept> list=new ArrayList<>();
        for(String s:split){
            DbChatGroupDept dept=new DbChatGroupDept();
            dept.setDeptId(s);
            dept.setOpenConversationId(openConversationId);
            list.add(dept);
        }

        saveOrUpdateBatch(list);
        DbChatGroup group=new DbChatGroup();
        group.setOpenConversationId(openConversationId);
        group.setDeptNames(deptNames);
        dbChatGroupService.updateById(group);
    }

    @Override
    public List<String> getDeptIds(String openConversationId) {
        DbChatGroupDeptQueryCriteria criteria=new DbChatGroupDeptQueryCriteria();
        criteria.setOpenConversationId(openConversationId);
        List<DbChatGroupDept> dbChatGroupDepts = queryAll(criteria);
        List<String> deptIds=new ArrayList<>();
        dbChatGroupDepts.forEach(dbChatGroupDept -> {
            deptIds.add(dbChatGroupDept.getDeptId());
        });
        return deptIds;
    }

    @Override
    public void syncNoGroupUserDept() {
        List<DbDeptUserDto> deptUsers = baseMapper.getNoGroupUserDept();
        Map<String,StringBuffer> map=new HashMap<>();
        for(DbDeptUserDto deptUser: deptUsers){

            List<String> deptIdList = deptService.findDeptIdToParentIdList(deptUser.getDeptId());

            DbChatGroupDeptQueryCriteria criteria=new DbChatGroupDeptQueryCriteria();
            criteria.setDeptId(deptIdList);
            List<DbChatGroupDept> dbChatGroupDepts = queryAll(criteria);
            if(UtilValidate.isNotEmpty(dbChatGroupDepts)){
                DbChatGroupDept group = dbChatGroupDepts.get(0);
                if(map.containsKey(group.getOpenConversationId())){
                    StringBuffer buffer = map.get(group.getOpenConversationId());
                    buffer.append(","+deptUser.getUserId());
                }else{
                    StringBuffer s=new StringBuffer();
                    s.append(deptUser.getUserId());
                    map.put(group.getOpenConversationId(),s);
                }
            }

        }
        if(map.size()>0){
            System.out.println("----新员工入群数据:");
            System.out.println(JSONObject.parseObject(JSONObject.toJSONString(map)));

            map.forEach((key,value)->{
                dbChatGroupUserService.addGroupUser(key, value.toString());
            });
        }

    }


    @Override
    public void syncNoGroupUserDeptTest() {
        List<DbDeptUserDto> deptUsers = baseMapper.getNoGroupUserDept();
        Map<String,StringBuffer> map=new HashMap<>();
        for(DbDeptUserDto deptUser: deptUsers){

            List<String> deptIdList = deptService.findDeptIdToParentIdList(deptUser.getDeptId());

            DbChatGroupDeptQueryCriteria criteria=new DbChatGroupDeptQueryCriteria();
            criteria.setDeptId(deptIdList);
            List<DbChatGroupDept> dbChatGroupDepts = queryAll(criteria);
            if(UtilValidate.isNotEmpty(dbChatGroupDepts)){
                DbChatGroupDept group = dbChatGroupDepts.get(0);
                if(map.containsKey(group.getOpenConversationId())){
                    StringBuffer buffer = map.get(group.getOpenConversationId());
                    buffer.append(","+deptUser.getUserId());
                }else{
                    StringBuffer s=new StringBuffer();
                    s.append(deptUser.getUserId());
                    map.put(group.getOpenConversationId(),s);
                }
            }

        }
        System.out.println("----新员工入群数据:");
        System.out.println(JSONObject.parseObject(JSONObject.toJSONString(map)));

    }

    @Override
    public void syncNoGroupUserDept(String userId) {
        Map<String,StringBuffer> map=new HashMap<>();

        DbDeptUserQueryCriteria deptUserQueryCriteria=new DbDeptUserQueryCriteria();
        deptUserQueryCriteria.setUserId(userId);
        List<DbDeptUser> dbDeptUsers = dbDeptUserService.queryAll(deptUserQueryCriteria);
        DbDeptUser deptUser=null;
        if(UtilValidate.isNotEmpty(dbDeptUsers)){
            deptUser=dbDeptUsers.get(0);
        }

        List<String> deptIdList = deptService.findDeptIdToParentIdList(deptUser.getDeptId());

        DbChatGroupDeptQueryCriteria criteria=new DbChatGroupDeptQueryCriteria();
        criteria.setDeptId(deptIdList);
        List<DbChatGroupDept> dbChatGroupDepts = queryAll(criteria);
        if(UtilValidate.isNotEmpty(dbChatGroupDepts)){
            DbChatGroupDept group = dbChatGroupDepts.get(0);
            if(map.containsKey(group.getOpenConversationId())){
                StringBuffer buffer = map.get(group.getOpenConversationId());
                buffer.append(","+deptUser.getUserId());
            }else{
                StringBuffer s=new StringBuffer();
                s.append(deptUser.getUserId());
                map.put(group.getOpenConversationId(),s);
            }
        }
        if(map.size()>0) {
            log.info("----新员工入群数据:", map);
        }
    }
}
